layui.use(['layer','form','table'], function(){
	var form = layui.form,
	layer = layui.layer,
	table = layui.table,
	$ = layui.$;
	var laytpl = layui.laytpl;
	layui.result_arr = []//选中维修配件接口返回集合
	layui.stock_id = []//选中的stock_id集合
	layui.price = 0//配件费用
	layui.have_id = []//拥有的id集合
	layui.del_id = []//删除的商品id集合
	console.log(111111)
	/*@获取repair_id*/
	var repair_id = ($('input[name="repair_id"]').val() > 0) ? $('input[name="repair_id"]').val() : 0
	/*@维修配件table*/
	table.render({
	    elem: '#repair-goods',
	    id: 'repair_goods',
	    url: '/repair/goods/repair_goods/ty/edit', //数据接口
	    page: false, //开启分页
	    limit: 'limit',
	    where: {repair_id: repair_id},
	    cols: [[ //表头
	    	{field: 'goods_id', title: '序号'},
	    	{field: 'goods_sn', title: '产品编码'},
	    	{field: 'goods_name', title: '产品名称'},
	    	{title: '数量', width: 120, toolbar: '#number'},
	    	{field: 'unit', title: '单位'},
	    	{field: 'selling_price', title: '零售单价(元)'},
	    	{title: '剩余库存', toolbar: '<div><span class="number">{{d.number}}</span></div>'},
	    	{title: '操作', width: 100, align:'center', toolbar: '#change-oper'},
	    ]],
	    /*渲染后回调*/
	    done: function(res){
	    },
	    /*渲染前，请求成功后回调*/
	    parseData: function(res){
	    	if(res.code === 0){
	    		layui.result_arr = res.data
		    	for(var i = 0;i < layui.result_arr.length;++i){
		    		layui.have_id.push(layui.result_arr[i].stock_id)
		    		layui.price += Number(layui.result_arr[i].selling_price*100)*Number(layui.result_arr[i].num)/100
		    	}
	    	}
	    }
	});
	/*@已选维修配件table*/
	table.render({
	    elem: '#repair-bind-goods',
	    // id: 'repair_goods',
	    url: '/repair/goods/repair_goods', //数据接口
	    page: false, //开启分页
	    limit: 'limit',
	    where: {repair_id: repair_id},
	    cols: [[ //表头
	    	{field: 'repair_goods_id', title: '序号'},
	    	{field: 'goods_sn', title: '产品编码'},
	    	{field: 'goods_name', title: '产品名称'},
	    	{field: 'num', title: '数量'},
	    	{field: 'unit', title: '单位'},
	    	{field: 'selling_price', title: '零售单价(元)'},
	    	{title: '剩余库存', toolbar: '<div><span class="number">{{d.number}}</span></div>'},
	    ]],
	    /*渲染后回调*/
	    done: function(res){
	    },
	    /*渲染前，请求成功后回调*/
	    parseData: function(res){
	    }
	});
	/*@表单验证*/
	form.verify({
		repair_sn: function(value){
			if(value == ''){
				return '维修编号丢失';
			}
		},
		user_sn: function(value){
			if(value == ''){
				return '请选择相似客户';
			}
		},
		is_prote: function(value, elem){
			if( $('input[name="is_prote"]:checked').length == 0 ){
				return '请选择保修类型';
			}
		},
		total_days: function(value){
			if(Number(value) < 1 && Number(value) > 50000){
				return '请输入1-50000之间的数字';
			}
		},
		pay_type: function(value){
			if( $('input[name="pay_type"]:checked').length == 0 ){
				return '请选择支付方式';
			}
		},
		repair_money: function(value){
			var repair_money = $('input[name="repair_money"]').val()
			var parts_money = $('input[name="parts_money"]').val()
			var people_money = $('input[name="people_money"]').val()
			if(Number(repair_money) < Number(parts_money)){
				return '维修总金额不得低于配件费用';
			}
			var money1 = Number(parts_money) + Number(people_money)
			if(Number(repair_money) != money1){
				return '配件费用+人工费用不等于维修总金额';
			}
			var actual_money = $('input[name="actual_money"]').val()
			if(Number(actual_money) > Number(repair_money)){
				return '支付金额不得大于维修总金额';
			}
			var stay_money = $('input[name="stay_money"]').val()
			var money2 = Number(stay_money) + Number(actual_money)
			if(Number(repair_money) != money2){
				return '已支付金额+待支付金额不等于维修总金额';
			}

		},
		actual_money: function(value){
			var repair_money = $('input[name="repair_money"]').val()
			var actual_money = $('input[name="actual_money"]').val()
			if(Number(actual_money) > Number(repair_money)){
				return '支付金额不得大于维修总金额';
			}
		}
	});
	/*@客户名字输入*/
	write_username = function (obj){
		var v = $(obj).val()
		$.post('/user/user/similar',{username: v},function(data){
			$('#user-sn').html('')
			if(data.code === 1){
				var html = '';
				for(var i = 0;i < data.msg.length;++i){
					html += '<span class="chakan span_nav" style="cursor:pointer;" onclick="xadmin.open(\'客户详情\',\'/user/user/details/ids/'+data.msg[i].user_sn+'\')">'+data.msg[i].user_sn+'</span>';
				}
				$('#user-sn').html(html)
			}
		})
	}
	/*@取消*/
	cancel_parts = function (obj,id){
      	layer.confirm('确认要取消吗？',function(index){
          	//发异步删除数据
          	$(obj).parents("tr").remove();
          	layer.msg('已取消!',{icon:1,time:1000});
      	});
  	}
  	/*@商品库存判断*/
  	if_number_fun = function (data){
  		for(var i = 0;i < layui.result_arr.length;++i){
  			if(Number(layui.result_arr[i].number) == 0 || (Number(layui.result_arr[i].number) < Number(layui.result_arr[i].num)) ){
  				layer.alert('商品：'+layui.result_arr[i].goods_name+',库存不够',{icon: 5, title: '错误提示'});
  				return false
  			}
  		}
  	} 
	/*@表单提交*/
	/*保存*/
	form.on('submit(baocun)',function(data){
		data.field.state = 0
		repair_add_fun(data)
	});
	/*等待维修配件*/
	form.on('submit(dengdai)',function(data){
		data.field.state = 1
		repair_add_fun(data)
	});
	/*确认维修*/
	form.on('submit(queren)',function(data){
		data.field.state = 3
		if( if_number_fun(data) === false ) return
		repair_add_fun(data)
	});
	/*编辑维修*/
	form.on('submit(update)',function(data){
		// if( if_number_fun(data) === false ) return
		repair_up_fun(data)
	});
	/*提交*/
	repair_add_fun = function (data){
		data.field.goods = layui.result_arr
		$.post('/repair/repair/repair_add',data.field,function(msg){
            if(msg.code === 1){
            	layer.msg('添加成功',{icon: 6, time: 2000},function(){
            		// /*打开新ifram tab*/
            		// xadmin.parent_add_tab(msg.msg,msg.url)
            		// /*关闭现有ifram tab*/
            		// xadmin.del_tab();
            		parent.location.reload();
            	})
            }else{
            	layer.alert(msg.msg, {icon: 5, title: '错误提示'})

            }
            
        })
	}
	/*编辑*/
	repair_up_fun = function (data){
		data.field.goods = layui.result_arr
		data.field.del = layui.del_id.length > 0 ? layui.del_id : ''
		data.field.ty = 'edit'
		console.log(data.field)
		$.post('/repair/repair/repair_edit',data.field,function(msg){
			if(msg.code === 1){
				layer.msg(msg.msg,{icon: 6, time: 1000},function(){
					
					window.parent.location.reload()
					parent.parent.layui.table.reload('table_list')
				})
            }else{
            	layer.alert(msg.msg, {icon: 5, title: '错误提示'})

            }
		})
	}
	/*@select选择监听*/
	form.on('select(select)',function(data){
		var name = $(data.elem).attr('name')
		if(name == 'category_name'){
			field = 'brand_name';
			title = '请选择设备品牌'
			$('select[name="brand_name"]').html('')
		}else if(name == 'brand_name'){
			field = 'marker';
			title = '请选择设备型号'
		}
		$('select[name="marker"]').html('')
		if(data.value != ''){
			var arr = data.value.split('@@')
			data.value = arr[0]
			sun_cate(arr[1], field, title)
		}else{
			form.render("select");
		}
	})
	/*@获取子级分类ajax*/
	sun_cate = function(fid, field, title){
		
		$.post('/repair/fault/sun_cate',{fid: fid},function(data){
			if(data.code === 0){
				layer.msg(data.msg, {icon: 2, time: 1000})
				return
			}
			var html = '';
			html += '<option value="">'+title+'</option>';
			if(data.data.length > 0){
				for(var i = 0;i < data.data.length;++i){
					html += '<option value="'+data.data[i].describes+'@@'+data.data[i].fault_id+'">'+data.data[i].describes+'</option>';
				}
			}
			$('select[name="'+field+'"]').html(html)
			form.render("select");
		})
	}
	/*@监听工具*/
	table.on('tool(list)', function(obj_tr){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
	  	var data = obj_tr.data; //获得当前行数据
	  	var layEvent = obj_tr.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
	  	var tr = obj_tr.tr; //获得当前行 tr 的DOM对象
	  	console.log(data)
	  	/*@事件监听*/
	  	if(layEvent === 'cencel'){ //取消
	  		layer.confirm('确定取消', {icon: 3,title: '提示'}, function(index){
	  			/*@数据处理*/
	  			var ind = $.inArray( data.stock_id, layui.stock_id)
	  			var ind_1 = $.inArray( data.stock_id, layui.stock_id)
	  			var ind_2 = $.inArray( data.stock_id, layui.have_id)
	  			var ind_3 = $.inArray( data.stock_id, layui.del_id)
	  			if( Number(ind_1) >= 0 || Number(ind_2) >= 0){/*存在*/
	  				if(ind_1 >= 0){
	  					layui.stock_id.splice(ind_1,1);
	  				}
	  				if(ind_2 >= 0 && ind_3 == -1){
	  					layui.del_id.push(data.stock_id)
	  					// layui.have_id.splice(ind_2,1);
	  				}
	  				for(var i = 0;i < layui.result_arr.length;++i){
	  					if(layui.result_arr[i].stock_id == data.stock_id){
	  						layui.result_arr.splice(i,1);
	  					}
	  				}
	  			}
	  			/*@dome操作*/
	  			var price = data.selling_price * data.num
	  			layui.cut_price(price)
	  			$(tr).remove()
	  			layer.close(index)
	  			repair_money_fun()
	  		})
	  	}else if(layEvent === 'add_num'){/*添加数量*/
	  		var len = $(tr).index()
	  		var num = $(tr).find('.num').text()
	  		++num
	  		let num_add = Number(num) - Number(data.old_num)
	  		if(num_add > data.number){
	  			layer.msg('剩余库存不足', {icon: 5})
	  			return
	  		}
	  		let number = $(tr).find('.number').text()
	  		$(tr).find('.number').text(--number)
	  		$(tr).find('.num').text(num)
	  		layui.result_arr[len].num = num
	  		layui.add_price(data.selling_price)
	  		repair_money_fun()
	  	}else if(layEvent === 'cut_num'){/*减少数量*/
	  		if(Number(data.num) <= 1){
				layer.msg('已选数量不能小于1', {icon: 2, time: 1000})
				return
			}
			for(var i = 0;i < layui.result_arr.length;++i){
				if(layui.result_arr[i].stock_id == data.stock_id){
					layui.result_arr[i].num = Number(layui.result_arr[i].num) - 1

					data.num = Number(layui.result_arr[i].num)
				}
			}
			let number = Number($(tr).find('.number').text())
	  		$(tr).find('.number').text(++number)
			layui.cut_price(data.selling_price)
			$(tr).find('.num').text(data.num)
			repair_money_fun()
	  	}
	});
	/*@配件费用处理*/
	layui.cut_price = function(price){
		layui.price = Number(layui.price) - Number(price)
	  	$(".parts_money").text(layui.price)
	  	$('input[name="parts_money"]').val(layui.price)
	}
	layui.add_price = function(price){
		layui.price = Number(layui.price) + Number(price)
	  	$(".parts_money").text(layui.price)
	  	$('input[name="parts_money"]').val(layui.price)
	}
	/*@输入维修总金额*/
	repair_money_fun = function (){
		var parts_money = $('input[name="parts_money"]').val()
		var actual_money = $('input[name="actual_money"]').val()
		var repair_money = $('input[name="repair_money"]').val()
		if( Number(repair_money) < Number(parts_money) ){
			layer.alert('维修总金额不得低于配件费用',{icon: 5})
			return
		}
		people_money_fun(repair_money, parts_money)
		stay_money_fun(repair_money, actual_money)
	}
	/*@输入已支付金额*/
	actual_money_fun = function(){
		var actual_money = $('input[name="actual_money"]').val()
		var repair_money = $('input[name="repair_money"]').val()
		if( Number(actual_money) > Number(repair_money) ){
			layer.alert('支付金额不得大于维修总金额',{icon: 5})
			return
		}
		stay_money_fun(repair_money, actual_money)
	}
	/*@人工费用处理*/
	people_money_fun = function(repair_money, parts_money){
		var people_money = Number(repair_money) - Number(parts_money)
		$('input[name="people_money"]').val(people_money)
		$('.people_money').text(people_money)
	}
	/*@待支付金额处理*/
	stay_money_fun = function(repair_money, actual_money){
		var stay_money = Number(repair_money) - Number(actual_money)
		$('input[name="stay_money"]').val(stay_money)
		$('.stay_money').text(stay_money)
	}

	/************************************ 维修员 **********************************/
	/*维修中保存*/
	form.on('submit(art_baocun)',function(data){
		data.field.ty = 'main_edit'
		$.post('/repair/repair/main_repair_edit',data.field,function(msg){
			if(msg.code === 1){
				layer.msg(msg.msg,{icon: 6, time: 1000},function(){
					location.reload()
				})
            }else{
            	layer.alert(msg.msg, {icon: 5, title: '错误提示'})

            }
		})
	});
})